<template>
  <div class="bg-box">
    <div class="title">{{ plugin.t('create.codekey') }}</div>
    <t-select 
      v-model="data.code_key" 
      :options="options"
      :loading="loading" 
      @search="onOrder"
      filterable
      clearable
    >
      <template #prefixIcon>
        <t-icon name="root-list" style="margin-right: 8px" />
      </template>
    </t-select>
    <div class="info" style="height: 50px">
      <template v-if="order">
        <span class="wrap">
          <b>{{ order.money }}</b>
        </span>
        <span class="wrap">
          {{ order.time.format() }}
        </span>
      </template>
    </div>
  </div>
</template>
<script setup>
  import { ref, watch } from 'vue'
  import app from '@/app'
  import index from '../../index'
  import { get } from '@/api/store/order'
  import store from './store'

  const plugin = index.plugin
  const data = store.data
  const options = ref([])
  const order = ref(false)

  const loading = ref(false)
  
  // 加载订单
  const onOrder = code => {
    loading.value = true
    get({ code }).then(res => {
      options.value = res.data.map(item => {
        return {
          value: item.code,
          label: item.code,
          data: {
            money: app.money.format(item.money),
            time: app.time.load(item.created_at)
          }
        }
      })
      
      // 显示订单信息
      onOrderInfo()
    }).finally(() => {
      loading.value = false
    })
  }

  // 显示订单信息
  const onOrderInfo = () => {
    const select = options.value.find(item => item.value == data.value.code_key)
    order.value = select ? select.data : false
  }

  // 改变选择
  watch(() => data.value.code_key, () => onOrderInfo())

  // 自动搜索
  onOrder(data.value.code_key)
</script>